package com.epi.one.basic.log;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.*;

/**
 * @author dxy
 * @version 1.0
 */
public class WinHandler extends StreamHandler {
    public WinHandler() {
        var output = new JTextArea(20,60);
        setOutputStream(new OutputStream() {
            @Override
            public void write(int b) throws IOException {}
            public void write(byte[] b, int off, int len) {
                output.append(new String(b, off, len));
            }
        });
        // 显示 Swing 窗口
        SwingUtilities.invokeLater(() -> {
            JFrame frame = new JFrame("日志窗口");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.add(new JScrollPane(output));
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        });
    }

    @Override
    public void flush() {
        System.out.println("flush() 被调用了");
        super.flush();
    }

    @Override
    public void close() throws SecurityException {
        System.out.println("close() 被调用了");
        super.close();
    }


    // 重写 publish：每条日志都立即刷新显示
    @Override
    public void publish(LogRecord record) {
        super.publish(record);
        flush();
    }

    @Override
    public boolean isLoggable(LogRecord record) {
        return record.getLevel() == Level.SEVERE;
    }
}
